package net.oschina.snmputil.iputils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.SystemUtils;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

/**
 * 
 * @author zdc
 *
 */
public class PingerUtils {
	static {
		PropertyConfigurator.configure("config/log4j.properties");
	}
	private static final Logger logger = Logger
			.getLogger(PingerUtils.class);
	/** * 要ping的主机 */
	private String remoteIpAddress;
	/** * 设置ping的次数 */
	private final int pingTimes;
	/** * 设置超时 */
	private int timeOut;
	 public static String getUTF8StringFromGBKString(String gbkStr) {  
		       
		             try {
						return new String(getUTF8BytesFromGBKString(gbkStr), "UTF-8");
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					return gbkStr;  
		         
		     }  
		      
		   public static byte[] getUTF8BytesFromGBKString(String gbkStr) {  
		        int n = gbkStr.length();  
		        byte[] utfBytes = new byte[3 * n];  
		        int k = 0;  
		        for (int i = 0; i < n; i++) {  
		           int m = gbkStr.charAt(i);  
		           if (m < 128 && m >= 0) {  
		                utfBytes[k++] = (byte) m;  
		              continue;  
		           }  
		           utfBytes[k++] = (byte) (0xe0 | (m >> 12));  
		           utfBytes[k++] = (byte) (0x80 | ((m >> 6) & 0x3f));  
		             utfBytes[k++] = (byte) (0x80 | (m & 0x3f));  
		        }  
		        if (k < utfBytes.length) {  
		        byte[] tmp = new byte[k];  
		           System.arraycopy(utfBytes, 0, tmp, 0, k);  
		           return tmp;  
		        }  
		        return utfBytes;  
		     }  


	/** * 构造函数 * * @param remoteIpAddress * @param pingTimes * @param timeOut */
	public PingerUtils(String remoteIpAddress, int pingTimes, int timeOut) {
		super();
		this.remoteIpAddress = remoteIpAddress;
		this.pingTimes = pingTimes;
		this.timeOut = timeOut;
	}

	/** * 测试是否能ping通 * @param server * @param timeout * @return */
	public boolean isReachable() {
		BufferedReader in = null;
		Runtime r = Runtime.getRuntime(); // 将要执行的ping命令,此命令是windows格式的命令
		// System.out.println(r.);
		String pingCommand = null;
		if (SystemUtils.IS_OS_WINDOWS) {
			pingCommand = "ping " + remoteIpAddress + " -n " + pingTimes
					+ " -w " + timeOut;
		} else if (SystemUtils.IS_OS_LINUX) {
			pingCommand = "ping " + remoteIpAddress + " -c " + pingTimes
					+ " -w " + timeOut;
		}
		try { // 执行命令并获取输出
			logger.debug(pingCommand);
		
			Process p = r.exec(pingCommand);
			if (p == null) {
				return false;
			}
			in = new BufferedReader(new InputStreamReader(p.getInputStream())); // 逐行检查输出,计算类似出现=23ms
																				// TTL=62字样的次数
			int connectedCount = 0;
			String line = null;
			while ((line = in.readLine()) != null) {
				

			//	logger.info(getUTF8StringFromGBKString(line));
			//	System.out.println(getUTF8StringFromGBKString(line));
				connectedCount += getCheckResult(line);
			} // 如果出现类似=23ms TTL=62这样的字样,出现的次数=测试次数则返回真
			System.out.println(connectedCount);
			return connectedCount >0;
		} catch (Exception ex) {
			ex.printStackTrace(); // 出现异常则返回假
			return false;
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * * 若line含有=18ms TTL=16字样,说明已经ping通,返回1,否則返回0.
	 * 
	 * @param line
	 *            * @return
	 */
	private static int getCheckResult(String line) { // System.out.println("控制台输出的结果为:"+line);
		if (SystemUtils.IS_OS_WINDOWS) {
			Pattern pattern = Pattern.compile("(TTL=\\d+)",
					Pattern.CASE_INSENSITIVE);
			Matcher matcher = pattern.matcher(line);
			while (matcher.find()) {
				return 1;
			}
			return 0;
		} else if (SystemUtils.IS_OS_LINUX) {
			Pattern pattern = Pattern.compile("(ttl=\\d+)",
					Pattern.CASE_INSENSITIVE);
			Matcher matcher = pattern.matcher(line);
			while (matcher.find()) {
				return 1;
			}
			return 0;
		}
		return 0;
	}

	public static void main(String[] args) {
		System.out.println(SystemUtils.IS_OS_LINUX);
		System.out.println(SystemUtils.IS_OS_WINDOWS_7);
		PingerUtils p = new PingerUtils("192.168.10.88", 5, 5000);
		System.out.println(p.isReachable());
	}
}
